<template>
  <!--问卷和报告填写-->
  <div id="questionAndReport" :catchtouchmove="show">
    <scroll-view :style="{'height': height+'px'}" :scroll-y="true">
      <div v-for="(item,index) in jsonData" :key="index">
        <div v-show="(index + 1) === currentIndex">
          <div class="titleWarp">
            <presentationtitle :state="false" :titleVal="index + 1 + '.' + item.question" />
          </div>
          <div v-for="(needitem,needindex) in item.child" :key="needindex">
            <div class="contWarp" v-if="needitem.question_type===1">
              <subject
                :type="1"
                :needindex="needindex"
                title="评价题"
                :selectVal="needitem.selectItem"
                :titleInfo="needitem.question"
                @typeClick="typeClick"
                :key="1"
              />
            </div>
            <div class="contWarp" v-if="needitem.question_type===2">
              <subject
                :type="2"
                :needindex="needindex"
                title="单选题"
                :selectVal="needitem.selectItem"
                :titleInfo="needitem.question"
                @typeClick="typeClick"
                :key="2"
              />
            </div>
            <div class="contWarp" v-if="needitem.question_type===3">
              <subject
                :type="3"
                :needindex="needindex"
                title="多选题"
                :selectVal="needitem.selectItem"
                :titleInfo="needitem.question"
                @typeClick="typeClick"
                :key="3"
              />
            </div>
            <div class="contWarp" v-if="needitem.question_type===4">
              <subject
                :type="4"
                :needindex="needindex"
                title="图片上传"
                :fileVal="needitem.selectItem"
                :titleInfo="needitem.question"
                @postImg="postImg"
                @delImg="delImg"
                :key="4"
              />
            </div>
            <div class="contWarp" v-if="needitem.question_type===5">
              <subject
                :type="5"
                :needindex="needindex"
                :fileVal="needitem.selectItem"
                title="视频上传"
                :titleInfo="needitem.question"
                @delVideo="delVideo"
                @postVideo="postVideo"
                :key="5"
              />
            </div>
            <div class="contWarp" v-if="needitem.question_type===6">
              <subject
                :type="6"
                :needindex="needindex"
                title="打分题"
                :numVal="needitem.score"
                :titleInfo="needitem.question"
                @dragNum="dragNum"
                :key="6"
              />
            </div>
            <div class="contWarp" style="overflow:hidden;" v-if="needitem.question_type===7">
              <subject
                :type="7"
                :needindex="needindex"
                title="描述题"
                :textareVal="needitem.answer"
                :titleInfo="needitem.question"
                @typeClick="typeClick"
              />
            </div>
            <div class="contWarp" v-if="needitem.question_type===8">
              <subject
                :type="8"
                :needindex="needindex"
                :min-date="optionsVal.receive_time"
                :max-date="optionsVal.maxDate"
                title="小票题"
                :textgroup="needitem.selectItem[0]"
                :fileVal="needitem.selectItemImg"
                @postImg="postImg"
                @delImg="delImg"
                :titleInfo="needitem.question"
                @ticketChange="ticketChange"
                :key="8"
              />
            </div>
          </div>
        </div>
      </div>
      <div class="contWarp footerContWarp">
        <div class="footerBtn">
          <div
            :class="currentIndex !==1 ? 'fttoerBtn_color' : 'fttoerBtn'"
            @click="currentIndex !==1 && (currentIndex = currentIndex-1)"
            v-if="currentIndex >= 1"
          >上一题</div>
          <div
            class="fttoerBtn_color"
            @click="currentIndex = currentIndex+1"
            v-if="currentIndex < jsonData.length"
          >下一题</div>
          <div
            class="fttoerBtn_color"
            v-if="currentIndex === jsonData.length"
            @click="postQuestionnaire"
          >提交</div>
        </div>
        <div class="menuNum">{{currentIndex}}/{{jsonData.length}}</div>
      </div>
      <van-toast id="van-toast" />
      <!-- 评价 弹出层 -->
      <van-popup
        :show="show"
        position="bottom"
        closeable
        close-icon-position="top-left"
        @close="onClose_footer"
      >
        <div class="popupTitle">评价</div>
        <div class="popupContent">
          <h6 v-if="report_type === 0">
            <img src="/static/imgs/pingfenlan.png" class="img" alt />
            <p>
              你确定给{{ restaurantName }}打
              <span style="color: #f15c48">{{ numVal }}</span>分？
            </p>
          </h6>
          <h6 v-if="report_type === 1">
            <img src="/static/imgs/pingfenlan.png" class="img" alt />
            <p>依据本次用餐体验，请选择此次对{{ restaurantName }}门店的评级：</p>
          </h6>
          <van-radio-group
            v-if="report_type === 1"
            :value="radioVal"
            @change="radioChange"
            style="display:flex;"
          >
            <van-radio class="radioLevel" icon-size="12" checked-color="#f15c48" name="A">
              <p>A</p>
            </van-radio>
            <van-radio class="radioLevel" icon-size="12" checked-color="#f15c48" name="B">
              <p>B</p>
            </van-radio>
            <van-radio class="radioLevel" icon-size="12" checked-color="#f15c48" name="C">
              <p>C</p>
            </van-radio>
            <van-radio class="radioLevel" icon-size="12" checked-color="#f15c48" name="D">
              <p>D</p>
            </van-radio>
          </van-radio-group>
        </div>
        <div class="popupContent">
          <template v-if="tags.length">
            <h6>
              <img src="/static/imgs/pingfenlan.png" class="img" alt />
              <p>您对{{ restaurantName }}的印象是下面哪几项</p>
            </h6>
            <div class="popupContent-options">
              <span
                v-for="(item,index) in tags"
                :class="item.active?'active':''"
                @click="tagsClick(item)"
                :key="index"
              >{{item.name}}</span>
              <span class="hidden"></span>
              <span class="hidden"></span>
              <span class="hidden"></span>
            </div>
          </template>
          <div class="popupContent-buttons">
            <button @click="onClose_footer">返回</button>
            <button :disabled="report_type === 1 && !radioVal" @click="subParams">确定</button>
          </div>
        </div>
      </van-popup>
    </scroll-view>
  </div>
</template>

<script>
import Toast from "@/../static/vant/toast/toast";
export default {
  data() {
    return {
      // needindex: 0,
      optionsVal: {},
      jsonData: [],
      optionPost: [],
      currentIndex: 1,
      show: false,
      numVal: 0,
      levelVal: "",
      radioVal: null,
      report_type: "",
      tags: [],
      restaurantName: "",
      height: ""
    };
  },
  methods: {
    radioChange(event) {
      this.radioVal = event.target["0"];
    },
    tagsClick(item) {
      item.active = !item.active;
    },
    typeClick(res) {
      const { needindex, index, type, text, indexarr } = res.target;
      if (type == "1" || type == "2") {
        //单选逻辑处理
        this.jsonData[this.currentIndex - 1].child[needindex].selectItem.map(
          (item, idx) => {
            this.jsonData[this.currentIndex - 1].child[needindex].selectItem[
              idx
            ].option_id = this.jsonData[this.currentIndex - 1].child[
              needindex
            ].selectItem[idx].id;
            if (idx == index) {
              this.jsonData[this.currentIndex - 1].child[needindex].selectItem[
                idx
              ].option_answer = 1;
            } else {
              this.jsonData[this.currentIndex - 1].child[needindex].selectItem[
                idx
              ].option_answer = 0;
            }
          }
        );
      } else if (type == "3") {
        // 多选
        this.jsonData[this.currentIndex - 1].child[needindex].selectItem.map(
          (item, idx) => {
            this.jsonData[this.currentIndex - 1].child[needindex].selectItem[
              idx
            ].option_id = this.jsonData[this.currentIndex - 1].child[
              needindex
            ].selectItem[idx].id;
            if (indexarr.includes(idx)) {
              this.jsonData[this.currentIndex - 1].child[needindex].selectItem[
                idx
              ].option_answer = 1;
            } else {
              this.jsonData[this.currentIndex - 1].child[needindex].selectItem[
                idx
              ].option_answer = 0;
            }
          }
        );
      } else if (type == "7") {
        this.jsonData[this.currentIndex - 1].child[needindex].selectItem = [
          {
            question_answer: text,
            question_id: this.jsonData[this.currentIndex - 1].child[needindex]
              .id
          }
        ];
      }
      //已经把选择过的选项进行标示 option_answer==1
    },
    // 小票题
    ticketChange(param) {
      const { modal, text, needindex, type } = param.target;
      this.jsonData[this.currentIndex - 1].child[needindex].selectItem[0] ||
        (this.jsonData[this.currentIndex - 1].child[needindex].selectItem = [
          {
            question_id: this.jsonData[this.currentIndex - 1].child[needindex]
              .id
          }
        ]);
      this.jsonData[this.currentIndex - 1].child[needindex].selectItem[0][
        modal
      ] =
        type === "number" ? Number(text) : text;
    },
    retutnArr() {
      //返回 单选 多选 评分 数组。
      return new Promise((resolve, reject) => {
        let arrReturn = [];
        this.jsonData.forEach(element => {
          let newarr = element.child; //将jsonData下的每个小题拼起来 数组拼接
          newarr.forEach(item => {
            if (item.selectItemImg)
              arrReturn = arrReturn.concat(item.selectItemImg);
            arrReturn = arrReturn.concat(item.selectItem);
          });
        });
        resolve(arrReturn);
      });
    },
    // 评价提交
    subParams() {
      this.retutnArr().then(res => {
        const tagsActive = [];
        this.tags.map(item => {
          // 已选标签
          if (item.active) {
            tagsActive.push(item.name);
          }
        });

        this.$http
          .post({
            url: "/mobile/api/subquestionnaire",
            data: {
              customer_id: wx.getStorageSync("userInfo").customer_id,
              id: this.optionsVal.receive_id,
              // consume:"",//多余的 注销
              // consume_num:"",//多余的 注销
              // food_num:"",//多余的 注销
              report_level: this.report_type === 1 ? this.radioVal : "",
              report_score: this.report_type === 0 ? this.numVal : "",
              report_tag: tagsActive.join(","),
              items: res
            }
          })
          .then(res => {
            if (res.code == "RX0000") {
              wx.navigateBack({
                delta: 2
              });
            } else {
              wx.showToast({
                icon: "none",
                title: res.msg
              });
            }
          });
      });
    },
    // 提交 开始评价
    postQuestionnaire() {
      this.numVal = 0;
      // 验证
      for (let i = 0; i < this.jsonData.length; i++) {
        // 循环每一大题
        for (let j = 0; j < this.jsonData[i].child.length; j++) {
          const childEle = this.jsonData[i].child[j]; // 循环每一大题中的每一小题
          if (
            childEle.question_type === 1 ||
            childEle.question_type === 2 ||
            childEle.question_type === 3
          ) {
            // 单选 多选
            const answerArr = childEle.selectItem.filter(
              selItem => selItem.option_answer === 1
            );
            if (answerArr.length === 0) {
              Toast({ message: "请完善题目", position: "bottom" });
              return false;
            }
          } else if (
            childEle.question_type === 4 ||
            childEle.question_type === 5 ||
            childEle.question_type === 6 ||
            childEle.question_type === 7
          ) {
            if (childEle.selectItem.length === 0) {
              Toast({ message: "请完善题目", position: "bottom" });
              return false;
            }
            if (childEle.question_type === 6 && this.report_type === 0) {
              this.numVal =
                Number(this.numVal) + Number(childEle.selectItem[0].score);
            }
          } else if (childEle.question_type === 8) {
            // 小票
            // （没有文字信息对象 || 没全部填写完成 ）|| (没有图片对象 || 一张都没有)
            if (
              childEle.selectItem.length === 0 ||
              Object.keys(childEle.selectItem[0]).length !== 7 ||
              (!childEle.selectItemImg || childEle.selectItemImg.length === 0)
            ) {
              Toast({ message: "请完善题目", position: "bottom" });
              return false;
            } else {
              const textValArr = Object.values(childEle.selectItem[0]).filter(
                item => item === ""
              ); // 获取对象内的空值
              if (textValArr.length !== 0) {
                Toast({ message: "请完善题目", position: "bottom" });
                return false;
              }
            }
          }
        }
      }
      this.show = true;
    },
    postImg(resdata) {
      const { path, needindex, type } = resdata.target;
      this.jsonData[this.currentIndex - 1].child[needindex].selectItemImg = [];
      path.forEach(element => {
        this.base64Fn(element, "image/jpeg").then(res => {
          this.$http
            .post({
              url: "/mobile/api/uploadfile",
              data: {
                customer_id: wx.getStorageSync("userInfo").customer_id,
                files: res
              }
            })
            .then(res => {
              if (res.code == "RX0000") {
                if (type === "type_8") {
                  // 小票里的图片
                  this.jsonData[this.currentIndex - 1].child[
                    needindex
                  ].selectItemImg.push({
                    question_id: this.jsonData[this.currentIndex - 1].child[
                      needindex
                    ].id,
                    pic_id: res.data.id
                  });
                } else {
                  // 上传图片
                  this.jsonData[this.currentIndex - 1].child[
                    needindex
                  ].selectItem.push({
                    question_id: this.jsonData[this.currentIndex - 1].child[
                      needindex
                    ].id,
                    file_id: res.data.id
                  });
                }
              } else {
                wx.showToast({
                  icon: "none",
                  title: "图片太大，请重新选择"
                });
              }
            });
        });
      });
    },
    // 上传视频
    postVideo(resdata) {
      const { file, needindex } = resdata.target;
      this.base64Fn(file.path, "video/mp4").then(res => {
        this.$http
          .post({
            url: "/mobile/api/uploadfile",
            data: {
              customer_id: wx.getStorageSync("userInfo").customer_id,
              files: res
            }
          })
          .then(res => {
            if (res.code == "RX0000") {
              this.jsonData[this.currentIndex - 1].child[
                needindex
              ].selectItem = [
                {
                  question_id: this.jsonData[this.currentIndex - 1].child[
                    needindex
                  ].id,
                  file_id: res.data.id
                }
              ];
            } else {
              wx.showToast({
                icon: "none",
                title: res.data
              });
            }
          });
      });
    },
    delImg(param) {
      const { path, needindex } = param.target;
      this.jsonData[this.currentIndex - 1].child[needindex].selectItem.forEach(
        (item, index) => {
          if (item.path === path) {
            this.jsonData[this.currentIndex - 1].child[
              needindex
            ].selectItem.splice(index, 1);
          }
        }
      );
    },
    delVideo(param) {
      const { path, needindex } = param.target;
      this.jsonData[this.currentIndex - 1].child[needindex].selectItem = [];
    },
    base64Fn(url, dataType) {
      return new Promise((resolve, reject) => {
        wx.getFileSystemManager().readFile({
          filePath: url, //选择图片返回的相对路径
          encoding: "base64", //编码格式
          success: res => {
            //成功的回调
            let base64 = "data:" + dataType + ";base64," + res.data;
            resolve(base64);
          }
        });
      });
    },
    // 拖拽分数
    dragNum(param) {
      const { num, needindex } = param.target;
      this.jsonData[this.currentIndex - 1].child[needindex].selectItem = [
        {
          question_id: this.jsonData[this.currentIndex - 1].child[needindex].id,
          score: num
        }
      ];
    },
    getNewData(jsondata, optionsVal) {
      this.returnLevel_bag(jsondata, optionsVal).then(res => {
        //返回大题加 大题下的 小题 注：不包括小题的选项
        this.jsonData = res;
      });
    },
    getQuestionnaire() {
      this.$http
        .post({
          url: "/mobile/api/questionnaire",
          data: {
            id:
              this.optionsVal.type == "1"
                ? this.optionsVal.id
                : this.optionsVal.receive_id,
            type: this.optionsVal.type
          }
        })
        .then(res => {
          if (res.code == "RX0000") {
            this.report_type = res.data.report_type;
            this.restaurantName = res.data.restaurant_name;
            if (res.data.task_tag !== "") {
              for (let i = 0; i < res.data.task_tag.split(",").length; i++) {
                this.tags.push({ name: res.data.task_tag[i], active: false });
              }
            } else {
              this.tags = [];
            }
            if (this.optionsVal.type == "1") {
              // 未填写过
              this.report_type === 1
                ? (this.radioVal = "")
                : (this.numVal = "");
            } else {
              // 驳回后提交 回显
              this.report_type === 1
                ? (this.radioVal = res.data.report_level)
                : (this.numVal = res.data.report_score);
              let arr = [];
              if (res.data.report_tag) arr = res.data.report_tag.split(",");

              for (let i = 0; i < arr.length; i++) {
                this.tags.forEach(item => {
                  item.nama === arr[i] && (item.active = true);
                });
              }
            }
            this.getNewData(res.data, this.optionsVal);
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg
            });
          }
        });
    },
    onClose_footer() {
      this.show = false;
    },
    returnLevel_bag(jsondata, optionsVal) {
      //返回大题加 大题下的 小题 注：不包括小题的选项
      return new Promise((reslove, reject) => {
        let needArry = []; //大题
        let subArry = []; //小题
        jsondata.questions.map((item, index) => {
          if (item.level === 1) {
            item.child = []; //存放子题目
            needArry.push(item);
          } else {
            item.selectItem = []; //如果当前小题有选项 selectItem==存放选项
            item.inputVal = ""; //当前小题答案
            if (optionsVal.type == "2") {
              // 回显数据
              if (item.question_type === 6) {
                // 打分题回显数据
                item.selectItem.push({
                  score: item.score,
                  question_id: item.id
                });
                if (this.report_type === 0) {
                  this.numVal = item.score;
                }
              }
              if (item.question_type === 7) {
                item.selectItem.push({
                  answer: item.answer,
                  question_id: item.id
                });
              }
              if (item.question_type === 8) {
                // 打分题回显数据
                item.selectItemImg = [];
                item.selectItem.push({
                  ticket_number: item.ticket_number,
                  waiter: item.waiter,
                  ticket_time: item.ticket_time,
                  diners: item.diners,
                  ticket_amount: item.ticket_amount,
                  ticket_net_receipts: item.ticket_net_receipts,
                  question_id: item.id
                });
              }
            }
            subArry.push(item);
          }
        });
        // 将选项 筛 到小问题下
        jsondata.option.length &&
          jsondata.option.map((item, index) => {
            let subindex = subArry.findIndex((nt, ni) => {
              return nt.id === item.questions_id;
            });
            // 选项回显数据 question_answer option_id
            if (optionsVal.type == "2") {
              // 回显数据
              if (item.question_answer === true) {
                item.option_answer = 1;
              } else {
                item.option_answer = 0;
              }
              item.option_id = subArry[subindex].id;
            }
            subArry[subindex].selectItem.push(item);
          });
        if (jsondata.files && jsondata.files.length) {
          jsondata.files.map((item, index) => {
            let subindex = subArry.findIndex((nt, ni) => {
              return nt.id === item.questions_id;
            });
            if (
              subArry[subindex].question_type === 4 ||
              subArry[subindex].question_type === 5
            ) {
              subArry[subindex].selectItem.push({
                question_id: subArry[subindex].id,
                path: item.path_url,
                file_id: item.file_id
              });
            } else if (subArry[subindex].question_type === 8) {
              subArry[subindex].selectItemImg.push({
                question_id: subArry[subindex].id,
                path: item.path_url,
                pic_id: item.file_id
              });
            }
          });
        }

        //将小问题 筛 到对应的大问题下
        subArry.map((item, index) => {
          let subindex = needArry.findIndex((nt, ni) => {
            return nt.id === item.pid;
          });
          needArry[subindex].child.push(item);
        });
        reslove(needArry);
      });
    }
  },
  onShow() {},
  onLoad(options) {
    this.optionsVal = options;
    if (this.optionsVal.receive_time) {
      this.optionsVal.receive_time = new Date(
        this.optionsVal.receive_time
      ).getTime();
    }
    this.optionsVal.maxDate = new Date().getTime();
    this.currentIndex = 1;
    this.show = false;
    this.radioVal = null;
    this.tags = [];
    this.jsonData = [];
    this.getQuestionnaire();
    wx.getSystemInfo({
      success: res => {
        this.height = res.windowHeight;
      }
    });
  }
};
</script>

<style lang='less'>
#questionAndReport {
  background: #f9f9f9;
  overflow: hidden;
  .titleWarp {
    width: 100%;
    margin: auto;
    background: #ffffff;
    padding: 14px 22px;
    overflow: hidden;
    box-sizing: border-box;
  }
  .contWarp {
    margin: 10px 0 0 0;
    .van-field__input--textarea {
      min-height: 98px;
      word-wrap: break-word;
    }
  }
  .footerContWarp {
    background: #ffffff;
    padding: 21px 0 6px 0;
    .footerBtn {
      font-size: 12px;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
      width: 220px;
      margin: auto;
      display: flex;
      justify-content: space-between;
      .fttoerBtn,
      .fttoerBtn_color {
        width: 89px;
        height: 27px;
        text-align: center;
        line-height: 27px;
        border-radius: 13px;
      }
      .fttoerBtn {
        background: rgba(204, 204, 204, 1);
      }
      .fttoerBtn_color {
        background-image: linear-gradient(to right, #126ff4, #0c3ff4);
      }
    }
    .menuNum {
      text-align: center;
      color: rgb(0, 0, 0);
      font-size: 12px;
      padding: 18px 0 12px 0;
    }
  }
  .popupTitle {
    color: #000000;
    text-align: center;
    font-size: 14px;
    font-weight: 600;
    margin-top: 15px;
  }
  .popupContent {
    margin: 20px 32px 0;
    font-size: 12px;
    h6 {
      display: flex;
      align-items: center;
      .img {
        width: 4px;
        height: 12px;
        float: left;
        margin-right: 10px;
      }
      p {
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(0, 0, 0, 1);
      }
    }
    &-options {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      margin-left: -9px;
      > span {
        width: 89px;
        height: 20px;
        border: 1px solid #ddd;
        text-align: center;
        font-size: 12px;
        color: #999999;
        font-weight: 400;
        display: inline-block;
        margin: 15px 0 0 0;
        &.active {
          background: #5696ff;
          color: #ffffff;
        }
        &.hidden {
          visibility: hidden;
        }
      }
    }
    &-buttons {
      padding: 30px 0;
      display: flex;
      > button {
        width: 89px;
        height: 27px;
        border: none;
        outline: none;
        font-size: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 30px;
        &:nth-of-type(1) {
          color: #fff;
          background: #ccc;
        }
        &:nth-of-type(2) {
          color: #fff;
          background: #055df8;
          margin-left: 30px;
        }
      }
    }
  }
  .upVideo {
    overflow: initial !important;
  }
  .videoIcon {
    position: relative;
    width: 78vw !important;
    margin-left: 1vw !important;
    height: 100px !important;
    margin-bottom: 8px !important;
    display: flex;
    -webkit-flex-direction: column;
    flex-direction: column;
    -webkit-align-items: center;
    align-items: center;
    -webkit-justify-content: center;
    justify-content: center;
    box-sizing: border-box;
  }
  .upVideo .van-uploader__upload {
    // width: 300px !important;
    // height: 80px !important;
    width: 78vw !important;
    margin-left: 1vw !important;
    height: 100px !important;
  }
  .upVideo .vanIcon {
    position: absolute;
    top: -8px;
    right: -8px;
    color: #969799;
    font-size: 18px;
    background-color: #fff;
    border-radius: 100%;
  }
  .radioLevel {
    p {
      width: 37px;
      padding: 9px 0px;
      padding-left: 10px;
    }
    .van-radio {
      .van-radio__icon-wrap {
        padding-left: 10px;
      }
      .van-radio__label {
        margin-left: 0px;
      }
    }
  }
}
</style>
